<template>
  <el-dialog :append-to-body="true" :close-on-click-modal="false" :before-close="cancel" :visible.sync="dialog"
             :title="'上传文件'+title" width="500px">
    <el-form ref="form" :rules="rules" size="small" label-width="80px">
      <!--   上传文件   -->
      <el-form-item label="上传">
        <el-upload
          ref="upload"
          class="upload-demo"
          drag
          :limit="1"
          :before-upload="beforeUpload"
          :auto-upload="false"
          :headers="headers"
          :on-success="handleSuccess"
          :on-error="handleError"
          :action="fileUploadPath+'?type=' + this.$route.query.type">
          <i class="el-icon-upload"/>
          <div class="el-upload__text">将文件拖到此处，或<em>添加文件</em></div>
          <div slot="tip" class="el-upload__tip">可上传任意格式文件，且不超过1G</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getToken } from '@/utils/auth'

  export default {
    data() {
      return {
        loading: false, dialog: false,
        headers: { 'Authorization': 'Bearer ' + getToken() },
        fileUploadPath: process.env.BASE_API + '/api/sysTool',
        rules: {}
      }
    },
    computed: {
      title: function() {
        switch (this.$route.query.type) {
          case 'plugin':
            return '常用插件'
          case 'template':
            return '模板'
          case 'use':
            return '使用手册'
        }
      }
    },
    methods: {
      cancel() {
        this.resetForm()
      },
      doSubmit() {
        this.$refs.upload.submit()
      },
      resetForm() {
        this.dialog = false
      },
      beforeUpload(file) {
        this.loading = true
        let isLt2M = true
        isLt2M = file.size / 1024 / 1024 < 1024
        if (!isLt2M) {
          this.$message.error('上传文件大小不能超过 1G!')
        }
        this.loading = false
        return isLt2M
      },
      handleSuccess(response, file, fileList) {
        this.dialog = false
        this.resetForm()
        this.$refs.upload.clearFiles()
        this.$parent.init()
      },
      // 监听上传失败
      handleError(e, file, fileList) {
        const msg = JSON.parse(e.message)
        this.$notify({
          title: msg.message,
          type: 'error',
          duration: 2500
        })
        this.loading = false
      }
    }
  }
</script>

<style scoped>

</style>
